package com.hp.it.pool.db;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.sql.SQLException;

public class ConnectionWapper implements InvocationHandler
{
	private Connection origin;

	private Connection wapper;

	private ConnectionPool connectionPool;

	ConnectionWapper(Connection conn, ConnectionPool connectionPool)
	{
		this.origin = conn;
		this.connectionPool = connectionPool;
	}

	Connection getConnection()
	{
		wapper = (Connection) Proxy.newProxyInstance(origin.getClass().getClassLoader(),
				new Class[] { Connection.class }, this);
		return wapper;
	}

	public Object invoke(Object proxy, Method method, Object[] args) throws SQLException, IllegalAccessException,
			InvocationTargetException
	{
		Object result = null;
		try
		{
			if (method.getName().equals("close"))
			{
				release();
			} else
			{
				result = method.invoke(origin, args);
			}
		} catch (SQLException e)
		{
			throw e;
		} catch (IllegalAccessException e)
		{
			throw e;
		} catch (InvocationTargetException e)
		{
			throw e;
		}
		return result;
	}

	private void release() throws SQLException
	{
		if (!connectionPool.releaseConnection(wapper))
		{
			origin.close();
			origin = null;
		}
	}
}